import 'package:flutter/material.dart';
import 'package:sy_flutter_alipay/sy_flutter_alipay.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:dio/dio.dart';
// import 'package:sy_flutter_wechat/sy_flutter_wechat.dart';

import '../widget/mq_button.dart';
import '../config/config.dart';

class PayPage extends StatefulWidget {

  final Map arguments;

  PayPage({Key key, this.arguments}) : super(key: key);

  @override
  _PayPageState createState() => _PayPageState();
}

class _PayPageState extends State<PayPage> {

  double allPrice = 0.0;

  List payList = [
    {
      'title': '支付宝支付',
      'name': 'alipay',
      'checked': true,
      'image': 'https://www.itying.com/themes/itying/images/alipay.png'
    },
    {
      'title': '微信支付',
      'name': 'wxpay',
      'checked': false,
      'image': 'https://www.itying.com/themes/itying/images/weixinpay.png'
    }
  ];

  @override
  void initState() { 
    super.initState();
    allPrice = double.parse(widget.arguments['allPrice']);
  }

  /// 执行支付
  _doPay(){
    var payWay = '';
    for(var i=0;i<payList.length;i++) {
      if (payList[i]['checked']) {
        payWay = payList[i]['name'];
      }
    }
    if(payWay == 'alipay') {
      _doAliPay();
    } else {
      _doWxPay();
    }
  }

  //执行支付宝支付
  _doAliPay() async {
    //http://agent.itying.com/alipay/
    var serverApi = '${Config.payDomain}/maque/pay/order?allPrice=$allPrice';
    var serverData = await Dio().get(serverApi);
    var payInfo = serverData.data; //签名后的订单信息

    print("----------------签名后的订单信息----------------");
    print(payInfo['result']);

    var result = await SyFlutterAlipay.pay(
      payInfo['result'],
      // urlScheme: '你的ios urlScheme', //前面配置的urlScheme
      isSandbox: true //是否是沙箱环境，只对android有效
    );

    print("----------------支付完成后返回的信息----------------");
    print(result);

    if(result['resultStatus'] == '9000') {
      Navigator.pushReplacementNamed(context, '/order');
    }

  }

  // 执行微信支付
  _doWxPay() {
    Fluttertoast.showToast(
      msg: "抱歉，未接入微信支付！",
      toastLength: Toast.LENGTH_SHORT,
      gravity: ToastGravity.CENTER,
      timeInSecForIosWeb: 1,
      backgroundColor: Colors.grey[600],
      textColor: Colors.white,
      fontSize: 16.0
    );
      /*
    * 1.请求后台取订单信息,后台请求微信统一下单接口
    * 2.app请求微信服务器
    * 3.微信给服务器回调通知
    * 4.微信给移动端返回结果
    */

    // String payInfo =
    //                 '{"appid":"wxf9909bde17439ac2","partnerid":"1518469211","prepayid":"wx120649521695951d501636f91748325073","package":"Sign=WXPay","noncestr":"1541976592","timestamp":"1541976592","sign":"E760C99A1A981B9A7D8F17B08EF60FCC"}';
    // SyPayResult payResult = await SyFlutterWechat.pay(
    //     SyPayInfo.fromJson(json.decode(payInfo)));
    // print(payResult);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('支付订单')
      ),
      body: Container(
        child: Column(
          children: <Widget>[
            /// Column里面直接写ListView有问题，需要在外面包裹个Container
            Container(
              height: 400,
              padding: EdgeInsets.all(20),
              child: ListView.builder(
                itemCount: payList.length,
                itemBuilder: (context, index) {
                  return Column(
                    children: <Widget>[
                      ListTile(
                        leading: Image.network(payList[index]['image']),
                        title: Text(payList[index]['title']),
                        trailing: payList[index]['checked'] ? Icon(Icons.check, color: Colors.blue) : Text(''),
                        onTap: () {
                          // 让payList里面的checked都等于false
                          setState(() {
                            for(var i=0;i<payList.length;i++) {
                              payList[i]['checked'] = false;
                            }
                            payList[index]['checked'] = true;
                          });
                        }
                      ),
                      Divider()
                    ]
                  );
                }
              )
            ),
            MqButton(
              text: '支付',
              color: Colors.red,
              height: 74,
              callback: () {
               _doPay();
              },
            )

        ]
      )
    )
    );
  }
}